<?php
/**
 * Created by PhpStorm.
 * Script Name: Rule.php
 * Create: 2023/1/6 13:49
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\validate;

use app\common\validate\Common;
use plugin\wechat\app\model\MpRule as RuleM;
use plugin\wechat\app\service\Mp as MpService;

class Rule extends Common
{
    public function __construct()
    {
        parent::__construct();
        $this->rule = array_merge([
            'id' => 'require|number',
            'keyword'  =>  'require|max:40|checkExists',
            'material_type'  => 'require|checkMaterialType',
            'material_id'  => 'require'
        ],
            $this->rule
        );
        $this->message = array_merge([
            'id.require' => 'id必须',
            'id.number' => 'id非法',
            'keyword.require' => '关键词必须',
            'keyword.max'     => '关键词不能超过40个字符',
            'keyword.checkExists'     => '关键词已存在',
            'material_type.require' => '回复类型必须',
            'material_type.checkMaterialType' => '回复类型错误',
            'material_id.require' => '请选择回复素材',
        ],
            $this->message
        );
    }

    /**
     * 验证matetial_type是否合法
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @author: fudaoji<fdj@kuryun.cn>
     */
    protected function checkMaterialType($value, $rule, $data){
        $types = MpService::replyTypes();
        return isset($types[$value]) ? true : false;
    }

    /**
     * 验证keyword是否被占用
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\db\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    protected function checkExists($value, $rule, $data){
        $where = [
            ['keyword', '=', $value],
            ['mp_id', '=', $data['mp_id']],
            ['company_id', '=', $data['company_id']],
        ];
        if(isset($data['id'])){
            $where[] = ['id', '<>', $data['id']];
        }
        $data = RuleM::where($where)->count();
        return $data ? false : true;
    }

    public function sceneAdd()
    {
        return $this->only(['keyword', 'material_type', 'material_id']);
    }

    public function sceneEdit()
    {
        return $this->only(['id', 'keyword', 'material_type', 'material_id']);
    }

}